//
//  CRSetController.m
//  CRChatRoom
//
//  Created by lanou3g on 15/11/18.
//  Copyright © 2015年 SecondGroup. All rights reserved.
//

#import "CRSetController.h"
#import "CRSetItem.h"
#import "CRSetArrowItem.h"
#import "CRSetGroup.h"
#import "CRSetSwithItem.h"
#import "CRProfileSetCell.h"
#import "CRSetHeaderView.h"
#import "CRProfileController.h"
#import "CRNavigationController.h"
#import "CRUserManager.h"
#import "CRLoginController.h"
#import "CRResetPasswordController.h"
#import "CRTool.h"
#import "CRUserDetailModel.h"
#import "QRCodeGenerator.h"
#import "ZBarReaderViewController.h"
#import "MBProgressHUD+MJ.h"
#import "SDImageCache.h"

@interface CRSetController () <CRSetHeaderViewDelegate, ZBarReaderDelegate>
/**
 *  用户信息模型
 */
@property (nonatomic, strong) CRUserDetailModel *detailModel;

@property (nonatomic, weak) CRSetHeaderView *headerView;

@property (nonatomic, weak) UIView *backView;
@property (nonatomic, weak) UIImageView *codeView;
@property (nonatomic, weak) UILabel *messageLabel;

@end

@implementation CRSetController



   // 第0组数据
- (void)setupGroup0
{
    CRSetItem *item00 = [CRSetArrowItem itemWithIcon:@"temp" title:@"个性装扮" desvcClass:nil];
    CRSetGroup *group0 = [[CRSetGroup alloc] init];
    group0.items = @[item00];
    [self.data addObject:group0];
}

    // 第1组数据
- (void)setupGroup1
{
    CRSetItem *item10 = [CRSetArrowItem itemWithIcon:@"temp" title:@"我的收藏" desvcClass:nil];
    CRSetItem *item11 = [CRSetArrowItem itemWithIcon:@"temp" title:@"我的相册"];
    CRSetItem *item12 = [CRSetItem itemWithIcon:@"temp" title:@"二维码"];
    CRSetItem *item13 = [CRSetItem itemWithIcon:@"temp" title:@"扫一扫"];
    item12.option = ^{
        
        [self setupBarcodeView];
        AVUser *currentUser = [AVUser currentUser];
        // 生成二维码
        self.codeView.image = [QRCodeGenerator qrImageForString:currentUser.objectId imageSize:self.codeView.frame.size.width];
    };
    
    item13.option = ^{
        // 创建扫描界面
        ZBarReaderViewController *readerVC = [[ZBarReaderViewController alloc] init];
        // 设置代理
        readerVC.readerDelegate = self;
        
        // 设置支持方向
        readerVC.supportedOrientationsMask = ZBarOrientationMaskAll;
        // 设置图片扫描器
        ZBarImageScanner *scanner = readerVC.scanner;
        
        // 配置图片扫描器
        [scanner setSymbology:ZBAR_I25 config:ZBAR_CFG_ENABLE to:0];
        [self presentViewController:readerVC animated:YES completion:nil];
    };
    
    CRSetGroup *group1 = [[CRSetGroup alloc] init];
    group1.items = @[item10, item11, item12, item13];
    [self.data addObject:group1];
}

    // 第2组数据
- (void)setupGroup2
{
    CRSetItem *item20 = [CRSetItem itemWithIcon:@"temp" title:@"检查新版本"];
    item20.option = ^{
        // 在这里做检查新版本的操作
        [UIView animateWithDuration:1.5 animations:^{
            [MBProgressHUD showMessage:@"当前为最新版本"];
        } completion:^(BOOL finished) {
            [MBProgressHUD hideHUD];
        }];
    };
    CRSetItem *item21 = [CRSetArrowItem itemWithIcon:@"temp" title:@"关于" desvcClass:nil];
    CRSetItem *item22 = [CRSetArrowItem itemWithIcon:@"temp" title:@"帮助" desvcClass:nil];
    CRSetItem *item23 = [CRSetItem itemWithIcon:@"temp" title:@"清除缓存"];
    item23.option = ^{
        
        
        [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
            
            [UIView animateWithDuration:1.5 animations:^{
                [MBProgressHUD showMessage:@"清除缓存成功"];
            } completion:^(BOOL finished) {
                [MBProgressHUD hideHUD];
            }];
            
        }];
    };

    CRSetGroup *group2 = [[CRSetGroup alloc] init];
    group2.items = @[item20, item21, item22, item23];
    [self.data addObject:group2];
  
}

// 第3组数据
- (void)setupGroup3
{
    CRSetItem *item30 = [CRSetSwithItem itemWithIcon:@"temp" title:@"夜间模式"];
    CRSetGroup *group3 = [[CRSetGroup alloc] init];
    group3.items = @[item30];
    [self.data addObject:group3];
}

- (void)setupGroup4
{
    CRSetItem *item40 = [CRSetItem itemWithIcon:@"temp" title:@"修改密码"];
    CRSetItem *item41 = [CRSetItem itemWithIcon:@"temp" title:@"退出登录"];
    item40.option = ^{
        
        UIAlertAction *phone = [UIAlertAction actionWithTitle:@"手机修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            CRResetPasswordController *resetPwdVC = [[CRResetPasswordController alloc] init];
            resetPwdVC.isResetByPhone = YES;
            [self showViewController:resetPwdVC sender:nil];
            
        }];
        
        UIAlertAction *oldPwd = [UIAlertAction actionWithTitle:@"原密码修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            CRResetPasswordController *resetPwdVC = [[CRResetPasswordController alloc] init];
            resetPwdVC.isResetByPhone = NO;
            [self showViewController:resetPwdVC sender:nil];
            
        }];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"修改方式" message:@"选择修改方式" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:phone];
        [alertController addAction:oldPwd];
        
        [self showViewController:alertController sender:nil];
        
        NSLog(@"重置密码");
        
    };
    
    item41.option = ^{
        // 退出登录帐号
        [[CRUserManager defaultManager] logoutProcedure];
        CRLoginController *loginVC = [[CRLoginController alloc] init];
        
        [UIApplication sharedApplication].keyWindow.rootViewController = loginVC;
//        [[NSUserDefaults standardUserDefaults] boolForKey:@"isAutoLogin"];
        
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isAutoLogin"];
        // 立即执行存入操作
        [[NSUserDefaults standardUserDefaults] synchronize];
    };
    CRSetGroup *group4 = [[CRSetGroup alloc] init];
    group4.items = @[item40, item41];
    [self.data addObject:group4];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1.标题
    self.title = @"设置";
    
    // 设置数据
    [self setupGroup0];
    [self setupGroup1];
    [self setupGroup2];
    [self setupGroup3];
    [self setupGroup4];
    
    [self setupSubViews];
    
    [self setupHeaderView];
    
    [self setupData];
    
}

#pragma mark >>>> 设置控件

- (void)setupData  {
    
    [CRTool getUserInfoWithobjectId:[AVUser currentUser].objectId withblock:^(NSDictionary *dict) {
        self.detailModel = [[CRUserDetailModel alloc] init];
        [self.detailModel setValuesForKeysWithDictionary:dict];
        
        self.headerView.userDetailM = self.detailModel;
        [self.tableView reloadData];
        
    }];
}

- (void)setupHeaderView {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 130)];
//    view.backgroundColor = [UIColor greenColor];
    
    CRSetHeaderView *headerView = [[CRSetHeaderView alloc] initWithFrame:CGRectMake(0, 0, kDefaultLeftViewShowWidth, 130)];
    headerView.delegate = self;
    [view addSubview:headerView];
    [self.tableView setTableHeaderView:view];
    
    self.headerView = headerView;
    
}
- (void)setupSubViews {
    // 设置背景图片
    [self setBackImageView:@"back_blue"];
    
    // 设置tableView的 contentInset
    self.tableView.contentInset = UIEdgeInsetsMake(150, 0, 110, 0);
    
}

/**
 *  设置背景图片
 *
 *  @param imageName 图片名
 */
- (void)setBackImageView:(NSString *)imageName {
    // 初始化一个背景imageView
    UIImageView *backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
    backImageView.userInteractionEnabled = YES;
    CGFloat backImageViewX = 0;
    CGFloat backImageViewY = 64;
    CGFloat backImageViewW = self.view.width;
    CGFloat backImageViewH = self.view.height - backImageViewY;
    backImageView.frame = CGRectMake(backImageViewX, backImageViewY, backImageViewW, backImageViewH);
    [self.tableView setBackgroundView:backImageView];
}

/**
 *  重写返回cell的方法
 *
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CRProfileSetCell *cell = [CRProfileSetCell cellWithTableView:tableView];
    
    // 2. 设置cell的数据
    CRSetGroup *group = self.data[indexPath.section];
    CRSetItem *item = group.items[indexPath.row];
    
    cell.item = item;
    cell.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    
    return cell;
}

#pragma mark >>>> 实现代理方法
- (void)didIconImageViewClick {
    NSLog(@"实现didIconImageViewClick代理方法 跳转到详情修改页面");
    
    CRProfileController *profileVC = [[CRProfileController alloc] init];
    profileVC.userDetailM = self.detailModel;
    CRNavigationController *naVC = [[CRNavigationController alloc] initWithRootViewController:profileVC];
    [self presentViewController:naVC animated:YES completion:nil];
}

#pragma mark >>>> 设置二维码view
- (void)setupBarcodeView {
    // 获取屏幕的中点
    CGPoint center = self.view.window.center;
    // 创建黑色遮罩背景
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(center.x, center.y, 0, 0)];
    // 获取当前window窗口
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.backView = backView;
    
    // 创建一个二维码窗口
    CGFloat viewW = 200;
    CGFloat viewH = viewW;
    CGFloat viewX = (CRScreenW - viewW) * 0.5;
    CGFloat viewY = viewW;
    UIImageView *codeView = [[UIImageView alloc] initWithFrame:CGRectMake(viewX, viewY, viewW, viewH)];
    self.codeView = codeView;
    
    CGFloat labelX = viewX;
    CGFloat labelY = CGRectGetMaxY(codeView.frame) + CRMargin;
    CGFloat labelW = viewW;
    CGFloat labelH = 30;
    UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(labelX, labelY, labelW, labelH)];
    messageLabel.text = @"扫码加我为好友";
    messageLabel.textAlignment = NSTextAlignmentCenter;
    messageLabel.backgroundColor = [UIColor colorWithWhite:0.298 alpha:0.7];
    messageLabel.textColor = [UIColor colorWithRed:0.400 green:1.000 blue:1.000 alpha:1.000];
    self.messageLabel = messageLabel;
    // 添加动画 显示view
    [UIView animateWithDuration:0.5 animations:^{
        backView.backgroundColor =[UIColor colorWithWhite:0.702 alpha:0.8];
        backView.frame = self.view.window.bounds;
        
        
    } completion:^(BOOL finished) {
        codeView.backgroundColor = [UIColor whiteColor];
        [backView addSubview:codeView];
        [backView addSubview:messageLabel];
    }];
    
    [window addSubview:backView];
    
     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackView:)];
    [backView addGestureRecognizer:tap];
    
}

#pragma mark >>>> 手势监听事件

- (void)tapBackView:(UIGestureRecognizer *)tap {
    [UIView animateWithDuration:0.6 animations:^{
        
        // 获取屏幕的中点
        CGPoint center = self.view.window.center;
        // 修改遮罩的frame
        self.backView.frame = CGRectMake(center.x, center.y, 0, 0);
        self.backView.alpha = 0;
        [self.codeView removeFromSuperview];
        [self.messageLabel removeFromSuperview];
    }];
    
}
#pragma mark >>>> ZBar代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    // 获取扫描结果
    id<NSFastEnumeration> result = [info objectForKey:ZBarReaderControllerResults];
    // 二维码信息
    ZBarSymbol *symbol;
    // 遍历
    for (symbol in result) {
        break;
    }
    self.codeView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    // 退出扫描界面
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

@end










